package chances.epg.session.ctrl;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.commons.utils.IPUtils;
import chances.epg.commons.utils.PathUtils;
import chances.epg.commons.utils.SpringWebUtils;
import chances.epg.config.EpgSiteContext;
import chances.epg.navigator.EpgConstants;
import chances.epg.navigator.history.HistoryEntry;
import chances.epg.navigator.history.NavigateHistory;
import chances.epg.navigator.history.NavigateHistoryFactory;
import chances.epg.navigator.service.NavigateUrlFactory;
import chances.epg.session.UserSession;
import chances.epg.session.UserSessionHelper;
import chances.epg.session.UserSessionService;

@Controller

public class LogonController {

	final static Logger loginLog = EpgLogFactory.getLogonlogger();
	@Autowired
	UserSessionService userSessionService;

	@Autowired
	NavigateUrlFactory navigateUrlFactory;

	@RequestMapping(path = "/{siteCode}/logon", method = RequestMethod.POST)
	public void logon(HttpServletRequest request, HttpServletResponse response, @ModelAttribute UserSession userSession,
			@PathVariable("siteCode") String siteCode) throws IOException {
		userSession.setCreateTime(System.currentTimeMillis());
		userSession.setLastActiveTime(System.currentTimeMillis());
		userSession.setSessionId(request.getSession().getId());
		userSession.setNetIp(IPUtils.getIpAddr(request));
		loginLog.info("{}|{}|{}|{}|{}|{}|{}", userSession.getNetIp(),userSession.getUserId(), userSession.getLoginUrl(), userSession.getEpgDomain(),
				userSession.getReturnUrl(), userSession.getUsertoken(),userSession.getSessionId());
		//userSessionService.add(userSession);
		//UserSessionHelper.saveUserIdToCookies(response, userSession.getUserId());
		UserSessionHelper.saveUserSessionToSession(request, userSession);
		if (StringUtils.isEmpty(userSession.getLoginUrl())) {
			EpgSiteContext epgSiteContext = EpgSiteContext.get(request.getServletContext(), siteCode);
			userSession.setLoginUrl(navigateUrlFactory.generateDefaultUrl(epgSiteContext));
		}
		response.sendRedirect(userSession.getLoginUrl());
	}

	@RequestMapping(path = "/{siteCode}/logon", method = RequestMethod.GET)
	public String logon(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("siteCode") String siteCode) {
		return PathUtils.join("/" + siteCode, "/common/logon.jsp");
	}

	@RequestMapping("{siteCode}/logout")
	public String logout(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("siteCode") String siteCode) {
		UserSession userSession = UserSessionHelper.getUserSession(request);
		if (userSession != null) {
			request.setAttribute("userSession", userSession);
		}
		UserSessionHelper.removeUserSessionFromSession(request);
		return PathUtils.join("/" + siteCode, "/common/logout.jsp");
	}

	@RequestMapping("/{siteCode}/back")
	public String back(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("siteCode") String siteCode) {
		UserSession userSession = UserSessionHelper.getUserSession(request);
		String userId = request.getParameter("userId");
		if(StringUtils.isNotEmpty(userId) && userSession == null){
			userSession = userSessionService.get(userId);
			UserSessionHelper.saveUserSessionToSession(request, userSession);
		}
		if(userSession!=null){
			NavigateHistory navigateHistory = getNavigateHistoryFactor(request).getHistory(request, userSession);
			request.setAttribute("navigateHistory", navigateHistory);
		}
		return PathUtils.join("/" + siteCode, "/common/back.jsp");
	}

	@RequestMapping("/{siteCode}/jump")
	public String jump(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("siteCode") String siteCode) {
		UserSession userSession = UserSessionHelper.getUserSession(request);
		NavigateHistory navigateHistory = getNavigateHistoryFactor(request).getHistory(request, userSession);
		String lfid = request.getParameter(EpgConstants.LEAVE_FOCUS_ID);
		HistoryEntry history = navigateHistory.peek();
		history.appendParameter(EpgConstants.ENTRY_FOCUS_ID, lfid);
		return PathUtils.join("/" + siteCode, "/common/jump.jsp");
	}

	public NavigateHistoryFactory getNavigateHistoryFactor(HttpServletRequest request) {
		return SpringWebUtils.findBean(request, NavigateHistoryFactory.class);

	}

}
